﻿//给QMS产品入库后应军检的数据
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:Wangjh
//create Date:2022-12-07
//Rewriter:
//Rewrite Date:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
using UFC.Common;
using UFC.DBUtility;
using System.Data;
using System.Text.RegularExpressions;
using System.Collections;
using System.Xml;

namespace MESQualityHistoryRecord
{
    class SendArmyInstoreToQMS
    {
        private const string m_cRecordType = "QMS_ArmyInStore";

        public void Excute() {

            //机加数据获取
            DataTable dt = GetJJArmyData();

            //装试数据获取，合并,后续龙斌做
            DataTable zsDT = GetZSArmyData();
            dt.Merge(zsDT);

            //循环处理数据
            foreach (DataRow dr in dt.Rows) {
                string strXML = DealSingleRow(dr);

                LogHelp.WriteLog("产品军检接口-推送XML:" + strXML);
                //调用质量系统的接口
                NewMesToQms.unifiedFunApi NewMTQ = new NewMesToQms.unifiedFunApi();
                //获取返回的xml
                string strResMsg = NewMTQ.mesToQmsAPI(strXML); //获取返回的xml;

                LogHelp.WriteLog("产品军检接口-返回XML:" + strResMsg);

                if (!string.IsNullOrWhiteSpace(strResMsg)) {
                    XmlDocument myxml = new XmlDocument();
                    myxml.LoadXml(strResMsg);
                    string xml = myxml.SelectSingleNode("RespMsg/document").InnerText;
                    myxml.LoadXml(xml);
                    string success = myxml.SelectSingleNode("TETTYP/RTYPE").InnerText;//
                    string message = myxml.SelectSingleNode("TETTYP/RTMSG").InnerText;//

                    //记录日志表
                    Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                        {"ParentId",dr["containerinstoreid"].ToString ()},{"RecordType",m_cRecordType},
                        {"ContainerID",dr["ContainerID"].ToString ()},{"ContainerName",dr["ContainerName"].ToString ()},
                        {"ProductName",dr["ProductName"].ToString ()},{"WorkflowStepName",""},
                        {"SendXml",strXML},{"ResXml",strResMsg}
                    };
                    if (success == "S")
                    {
                        recordPara.Add("IsSuccess", "0");//成功
                    }
                    else
                    {
                        recordPara.Add("IsSuccess", "1");//失败                    
                    }
                    OracleDAL.InserOtherSystemRecord(recordPara);
                }
                
            }

        }

        /// <summary>
        /// 生成对应xml
        /// </summary>
        /// <param name="strList">基本信息</param>
        /// <param name="checkResultDt">检测项</param>
        /// <param name="issueDt">集件信息</param>
        /// <param name="fileListDt">文件信息</param>
        /// <returns></returns>
        private string CreateXMLForArmyInStore(Dictionary<string, string> strList,DataTable checkResultDt ,DataTable issueDt,DataTable fileListDt)
        {

            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode senderNode = doc.CreateElement("sendSysName");
            senderNode.InnerText = "APP_MES";
            XmlNode rcvNode = doc.CreateElement("rcvSysName");
            rcvNode.InnerText = "APP_QMS";
            XmlNode extNode = doc.CreateElement("extConfig");
            extNode.AppendChild(doc.CreateElement("isReTry"));
            extNode.LastChild.InnerText = "false";
            extNode.AppendChild(doc.CreateElement("FunName"));
            extNode.LastChild.InnerText = "MES_Send_Service";
            headerNode.AppendChild(senderNode);
            headerNode.AppendChild(rcvNode);
            headerNode.AppendChild(extNode);
            ReqNode.AppendChild(headerNode);

            XmlNode root = doc.CreateElement("root");
            XmlNode qmsFun = doc.CreateElement("qmsFunName");
            qmsFun.InnerText = "MES_Send_ProductMilitaryCheckInfo";
            root.AppendChild(qmsFun );

            XmlNode documentNode = doc.CreateElement("document");
            ReqNode.AppendChild(documentNode);

            XmlNode qmsDocument = doc.CreateElement("qmsDocument");//具体业务内容
            
            foreach (KeyValuePair<string, string> _key in strList)
            {
                XmlNode data = doc.CreateElement(_key.Key );
                data.InnerText = _key.Value;
                qmsDocument.AppendChild(data); 
            } 
            //追加检测项信息
            XmlNode checkItemList = doc.CreateElement("checkResultList");
            foreach (DataRow dr in checkResultDt.Rows) {
                XmlNode checkItem = doc.CreateElement("CheckResult");

                XmlNode node = doc.CreateElement("checkNo");
                node.InnerText = dr["CheckNO"].ToString();
                checkItem.AppendChild(node);

                node = doc.CreateElement("checkPointName");
                node.InnerText = dr["CheckPointName"].ToString();
                checkItem.AppendChild(node);

                node = doc.CreateElement("checkPointNote");//有特殊符号需要用cdata
                node.AppendChild(doc.CreateCDataSection(dr["CheckPointNote"].ToString())); 
                checkItem.AppendChild(node);

                node = doc.CreateElement("drawingRequire");//有特殊符号需要用cdata
                node.AppendChild(doc.CreateCDataSection(dr["DrawingRequire"].ToString())); 
                checkItem.AppendChild(node);

                node = doc.CreateElement("workflowBaseName");
                node.InnerText = dr["WorkflowBaseName"].ToString();
                checkItem.AppendChild(node);

                node = doc.CreateElement("checkType");
                node.InnerText = dr["CheckType"].ToString();
                checkItem.AppendChild(node);

                node = doc.CreateElement("keyCheck");
                node.InnerText = dr["KeyCheck"].ToString();
                checkItem.AppendChild(node);

                node = doc.CreateElement("meopCheck");
                node.InnerText = dr["MeopCheck"].ToString();
                checkItem.AppendChild(node);

                node = doc.CreateElement("qualityCheck");
                node.InnerText = dr["QualityCheck"].ToString();
                checkItem.AppendChild(node);

                node = doc.CreateElement("checkPointResultNote");//有特殊符号需要用cdata
                node.AppendChild(doc.CreateCDataSection(dr["CheckPointResultNote"].ToString())); 
                checkItem.AppendChild(node);

                node = doc.CreateElement("checkerName");
                node.InnerText = dr["CheckerName"].ToString();
                checkItem.AppendChild(node);

                node = doc.CreateElement("checkDate");
                node.InnerText = dr["CheckDate"].ToString();
                checkItem.AppendChild(node);
                 
                /*
                string checkItemData = "";// "<root>";
                checkItemData += string.Format("<CheckNO>{0}</CheckNO>", dr["CheckNO"].ToString());
                checkItemData += string.Format("<CheckPointName>{0}</CheckPointName>", dr["CheckPointName"].ToString());
                checkItemData += string.Format("<CheckPointNote><![CDATA[{0}]]</CheckPointNote>", dr["CheckPointNote"].ToString());
                checkItemData += string.Format("<DrawingRequire><![CDATA[{0}]]</DrawingRequire>", dr["DrawingRequire"].ToString());
                checkItemData += string.Format("<WorkflowBaseName>{0}</WorkflowBaseName>", dr["WorkflowBaseName"].ToString());
                checkItemData += string.Format("<CheckType>{0}</CheckType>", dr["CheckType"].ToString());
                checkItemData += string.Format("<KeyCheck>{0}</KeyCheck>", dr["KeyCheck"].ToString());
                checkItemData += string.Format("<MeopCheck>{0}</MeopCheck>", dr["MeopCheck"].ToString());
                checkItemData += string.Format("<QualityCheck>{0}</QualityCheck>", dr["QualityCheck"].ToString());
                checkItemData += string.Format("<CheckPointResultNote><![CDATA[{0}]]</CheckPointResultNote>", dr["CheckPointResultNote"].ToString());
                checkItemData += string.Format("<CheckerName>{0}</CheckerName>", dr["CheckerName"].ToString());
                checkItemData += string.Format("<CheckDate>{0}</CheckDate>", dr["CheckDate"].ToString());
                //checkItemData += "</root>"; 
                checkItem.AppendChild(doc.CreateCDataSection (checkItemData ));
                */

                checkItemList.AppendChild(checkItem);
            }
            qmsDocument.AppendChild(checkItemList);

            //追加集件信息
            XmlNode CollectList = doc.CreateElement("collectMaterialList");
            foreach (DataRow dr in issueDt.Rows) {
                XmlNode collectItem = doc.CreateElement("CollectMaterial");
                
                XmlNode node = doc.CreateElement("childProductName");
                node.InnerText = dr["ChildProductName"].ToString();
                collectItem.AppendChild(node);

                node = doc.CreateElement("childProductDesc");
                node.InnerText = dr["ChildProductDesc"].ToString();
                collectItem.AppendChild(node);

                node = doc.CreateElement("childProductContainerName");
                node.InnerText = dr["ChildProductContainerName"].ToString();
                collectItem.AppendChild(node);

                node = doc.CreateElement("productType");
                node.InnerText = dr["ProductType"].ToString();
                collectItem.AppendChild(node);

                node = doc.CreateElement("qty");
                node.InnerText = dr["Qty"].ToString();
                collectItem.AppendChild(node);

                node = doc.CreateElement("confirmEmpoyeeName");
                node.InnerText = dr["ConfirmEmpoyeeName"].ToString();
                collectItem.AppendChild(node);

                node = doc.CreateElement("confirmDate");
                node.InnerText = dr["ConfirmDate"].ToString();
                collectItem.AppendChild(node);


                /*
                string collectItemData = "<root>";
                collectItemData += string.Format("<ChildProductName>{0}</ChildProductName>", dr["ChildProductName"].ToString());
                collectItemData += string.Format("<ChildProductDesc>{0}</ChildProductDesc>", dr["ChildProductDesc"].ToString());
                collectItemData += string.Format("<ChildProductContainerName>{0}</ChildProductContainerName>", dr["ChildProductContainerName"].ToString());
                collectItemData += string.Format("<ProductType>{0}</ProductType>", dr["ProductType"].ToString());
                collectItemData += string.Format("<Qty>{0}</Qty>", dr["Qty"].ToString());
                collectItemData += string.Format("<ConfirmEmpoyeeName>{0}</ConfirmEmpoyeeName>", dr["ChildProductDesc"].ToString());
                collectItemData += string.Format("<ConfirmDate>{0}</ConfirmDate>", dr["ConfirmDate"].ToString());
                collectItemData += "</root>"; 
                collectItem.AppendChild(doc.CreateCDataSection(collectItemData));
                */

                CollectList.AppendChild(collectItem);
            }
            qmsDocument.AppendChild(CollectList);
            //追加附件信息
            XmlNode DocumentList = doc.CreateElement("documentList");
            foreach (DataRow dr in fileListDt.Rows)
            {
                XmlNode fileItem = doc.CreateElement("document");


                XmlNode node = doc.CreateElement("fileID");
                node.InnerText = dr["FileID"].ToString();
                fileItem.AppendChild(node);

                node = doc.CreateElement("fileName");
                node.InnerText = dr["FileName"].ToString();
                fileItem.AppendChild(node);

                /*
                string fileItemData = "<root>";
                fileItemData += string.Format("<FileID>{0}</FileID>", dr["FileID"].ToString());
                fileItemData += string.Format("<FileName>{0}</FileName>", dr["FileName"].ToString());
                fileItemData += "</root>";
                collectItem.AppendChild(doc.CreateCDataSection(fileItemData));
                */

                DocumentList.AppendChild(fileItem);
            }
            qmsDocument.AppendChild(DocumentList);


            root.AppendChild(qmsDocument );

            string strRoot = root.OuterXml.Replace("]]>", "]]]]><![CDATA[>");//cdata嵌套，特殊处理

            documentNode.InnerXml = "<![CDATA[" + strRoot + "]]>";

            doc.AppendChild(ReqNode);
            return doc.InnerXml;
        }

        #region 机加数据处理
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        DataTable GetJJArmyData() {
            string strSql = @"select ci.containerinstoreid,cci.containerid,cci.workflowid,ci.aufnr MfgOrderName,ci.charg ContainerName,'' EngineNo ,ci.MATNR ProductName,ci.MAKTX ProductDesc,replace(ci.charg,ci.MATNR||'/') ProductBatchNo ,'WF-'||w.process_no||':'||w.workflowrevision WorkflowBaseName ,
ci.zhgsl CheckQualifiedQty ,cci.plannedstartdate PlanStartTime ,cci.plannedcompletiondate PlanFinishTime,'' StartTime,ci.createdate FinishTime,u2.ATTRIBUTEVALUE affiliatedFactory ,f.factoryName  
from containerinstore ci
left join workflow w on w.workflowid=ci.workflowid
left join containercurrentinfo cci on cci.containername=ci.charg
LEFT JOIN USERATTRIBUTE u2 ON u2.PARENTID =cci.FACTORYID AND u2.USERATTRIBUTENAME ='分厂代码'
LEFT JOIN Factory f on f.factoryid=cci.FACTORYID
left join WritetoOtherSystem ws on ws.parentid=ci.containerinstoreid and ws.recordtype='QMS_ArmyInStore'
where ci.isarmycheck=1 and ci.isuse=0 and ci.FEVOR<>603 and ws.parentid is null and rownum<500";
            return OracleHelper.Query(strSql).Tables[0];
        }
        /// <summary>
        /// 获取装试，整机入库需军检数据
        /// </summary>
        /// <returns></returns>
        DataTable GetZSArmyData() {
            var strSql = @"select ci.containerinstoreid,'' containerid,wf.workflowid,ci.aufnr MfgOrderName,ci.charg ContainerName,u.attributevalue EngineNo ,ci.MATNR ProductName,p.DESCRIPTION ProductDesc,
                replace(ci.charg,ci.MATNR||'/') ProductBatchNo ,'WF-'||wf.process_no||':'||wf.workflowrevision WorkflowBaseName ,
                ci.zhgsl CheckQualifiedQty ,m.plannedstartdate PlanStartTime ,m.plannedcompletiondate PlanFinishTime,'' StartTime,ci.createdate FinishTime,ci.FEVOR affiliatedFactory,f.factoryName   
                from containerinstore ci
                LEFT JOIN mfgorder m ON m.MFGORDERNAME =ci.AUFNR 
                LEFT JOIN Userattribute u ON u.parentid = m.mfgorderid AND u.userattributename='发动机' 
                LEFT JOIN product p ON p.productid = GET_SPLIT_MFGORDER_PRODUCTID(m.mfgorderid)
                LEFT JOIN Workflowbase wb1 ON wb1.workflowbaseid = p.workflowbaseid
                LEFT JOIN Workflow wf ON wf.workflowid = NVL(wb1.revofrcdid,p.workflowid)
                LEFT JOIN Factory f on f.factoryid=m.FACTORYID
                left join WritetoOtherSystem ws on ws.parentid=ci.containerinstoreid and ws.recordtype='QMS_ArmyInStore'
                where ci.isarmycheck=1 and ci.isuse=0 and ci.FEVOR=603 and ws.parentid is null and rownum<500";
            return OracleHelper.QueryTable(strSql,null);
        }

        /// <summary>
        /// 单行处理，并生成xml格式
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        string DealSingleRow(DataRow dr) {
            string re = "";

            //基本信息
            Dictionary<string, string> strList = new Dictionary<string, string>();
            //检测项信息
            DataTable checkResultDt = new DataTable();
            checkResultDt.Columns.AddRange(new DataColumn[] { new DataColumn("CheckNO"), new DataColumn("CheckPointName"), new DataColumn("CheckPointNote"), 
                new DataColumn("DrawingRequire"), new DataColumn("WorkflowBaseName"), new DataColumn("CheckType"), new DataColumn("KeyCheck"), new DataColumn("MeopCheck"), 
                new DataColumn("QualityCheck"), new DataColumn("CheckPointResultNote"), new DataColumn("CheckerName"), new DataColumn("CheckDate") });

            //集件信息
            DataTable issueDt = new DataTable();
            issueDt.Columns.AddRange(new DataColumn[] { new DataColumn("ChildProductName"), new DataColumn("ChildProductDesc"), new DataColumn("ChildProductContainerName"),
                new DataColumn("ProductType"), new DataColumn("Qty"), new DataColumn("ConfirmEmpoyeeName"), new DataColumn("ConfirmDate") });

            //文件信息
            DataTable fileListDt = new DataTable();
            fileListDt.Columns.AddRange(new DataColumn[] { new DataColumn("FileID"), new DataColumn("FileName") });

            //填充数据
            strList.Add("mfgOrderName", dr["MfgOrderName"].ToString());
            strList.Add("containerName", dr["ContainerName"].ToString());
            strList.Add("engineNo", dr["EngineNo"].ToString());
            strList.Add("productName", dr["ProductName"].ToString());
            strList.Add("productDesc", dr["productDesc"].ToString());//件号名称 add by longb 2023-04-20
            strList.Add("productBatchNo", dr["ProductBatchNo"].ToString());
            strList.Add("workflowBaseName", dr["WorkflowBaseName"].ToString());
            strList.Add("checkQualifiedQty", dr["CheckQualifiedQty"].ToString());
            strList.Add("planStartTime", dr["PlanStartTime"].ToString());
            strList.Add("planFinishTime", dr["PlanFinishTime"].ToString());
            strList.Add("startTime", dr["StartTime"].ToString());
            strList.Add("finishTime", dr["FinishTime"].ToString());
            strList.Add("affiliatedFactory", dr["affiliatedFactory"].ToString());//分厂代码 add by longb 2023-04-20
            strList.Add("factoryName", dr["factoryName"].ToString());//分厂名称 add by longb 2023-04-20

            //查询检测项数据并填充
            string strSql = @"select st.checkno,st.name CheckPointName,st.checkpointnotedis CheckPointNote,st.drawingrequiredis DrawingRequire,st.checktype,
st.meopcheck,st.keycheck,st.qualitycheck,sr.checkpointresultnotedis CheckPointResultNote,e.fullname CheckerName,sr.checkdate,
'WF-'||w.process_no||':'||w.workflowrevision WorkflowBaseName  from stepcheckpointresult sr
left join stepcheckpoint st on st.stepcheckpointid=sr.stepcheckpointid
left join workflowstep ws on ws.workflowstepid=st.workflowstepid
left join employee e on e.employeeid=sr.checkerid
left join workflow w on w.workflowid=ws.workflowid
where sr.containerid='{0}' and ws.workflowid='{1}'";
            checkResultDt = OracleHelper.Query(string.Format(strSql, dr["containerid"].ToString(), dr["workflowid"].ToString())).Tables[0];

            //集件信息
            strSql = @"select cci.mfgordername,cci.containername,cci.productname,cci.realcontainerno ProductBatchNo
,cci.workflowname||':'||cci.workflowrevision WorkflowBaseName,cl.productname ChildProductName,p.description ChildProductdesc,cl.productbatchno ChildProductContainerName,
decode(pi.parttype,0,'大件',1,'小件','其他') ProductType,il.issueqty Qty,e.fullname ConfirmEmpoyeeName,
to_char(il.createdate,'yyyy/mm/dd hh24:mi:ss') ConfirmDate,il.issueerpmaterialid from issueerpmaterial il 
left join enginepartplan ep on ep.containerid=il.containerid
left join containercurrentinfo cci on cci.containerid=il.containerid
left join workflowstep ws on ws.workflowstepid=il.workflowstepid
left join collecterpmaterial cl on cl.collecterpmaterialid=il.collecterpmaterialid
left join partmenuinfo pi on pi.partmenuinfoid=il.partmenuinfoid
left join productbase pb on pb.productname=cl.productname
left join product p on p.productid=pb.revofrcdid
left join employee e on e.employeeid=il.employeeid
where il.containerid='{0}'";
            issueDt = OracleHelper.Query(string.Format(strSql, dr["containerid"].ToString())).Tables[0];

            re = CreateXMLForArmyInStore(strList, checkResultDt, issueDt, fileListDt);


            return re;
            
        }

        #endregion
    }
}
